<template>
  <div>
    <HeaderView></HeaderView>
    <ListView>

      <template v-slot:list>
        <!--查询、添加按钮-->
        <div class="operate">
          <div class="from-box">
            <el-form :inline="true" :model="queryUserForm" class="demo-form-inline">
              <el-form-item label="昵称">
                <el-input size="small" clearable v-model="queryUserForm.user" placeholder="请输入昵称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" @click="queryUser" icon="el-icon-search">查询
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="add-box">
            <el-button size="small" @click="addWin = true" type="success" icon="el-icon-plus">增添</el-button>
          </div>
        </div>

        <!--表格-->
        <el-table
            :data="tableData"
            border
            style="width: 100%"
            max-height="600">
          <el-table-column
              prop="username"
              label="用户名"
              width="120">
          </el-table-column>
          <el-table-column
              prop="nickname"
              label="昵称"
              width="120">
          </el-table-column>
          <el-table-column
              prop="avatar"
              label="头像"
              width="150">
            <template slot-scope="{row}">
              <div v-if="row.avatar==='' || row.avatar.substring(0,33)!==tableImageUrl" class="el-image__error">
              </div>
              <div v-else class="el_image">
                <img :src="row.avatar" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column
              prop="accountNonLocked"
              label="账户是否被锁定"
              width="130">
            <template slot-scope="{row}">
              <el-tag type="success" plain>{{ row.accountNonLocked ? '否' : '是' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="enabled"
              label="账户启用状态"
              width="130">
            <template slot-scope="scope">
              <el-badge>
                <el-switch
                    @change="handleSwitch(scope.row)"
                    v-model="scope.row.enabled">
                </el-switch>
              </el-badge>
            </template>
          </el-table-column>
          <el-table-column
              prop="roles"
              label="关联角色"
              width="200">
            <template slot-scope="{row}">
              <el-badge v-if="row.roles.length!==0">
                <el-tag style="margin: 3px" v-for="(item,index) in row.roles" :key="index" type="primary" plain>
                  {{ item.describe }}
                </el-tag>
              </el-badge>
              <el-button @click="handleRoles(row)" style="margin: 2px" type="text" icon="el-icon-edit"></el-button>
            </template>
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="创建时间"
              width="220">
            <template slot-scope="{row}">
              {{ formatDate(new Date(row.createTime)) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="updateTime"
              label="更新时间"
              width="220">
            <template slot-scope="{row}">
              {{ formatDate(new Date(row.createTime)) }}
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="180">
            <template slot-scope="scope">
              <el-button
                  plain
                  size="small"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)">编辑
              </el-button>
              <el-button
                  plain
                  size="small"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--分页-->
        <div class="block">
          <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total=total>
          </el-pagination>
        </div>
      </template>
    </ListView>
    <!--添加用户-->
    <el-drawer
        title="新赠用户"
        :visible.sync="addWin"
        direction="rtl"
        size="40%"
        :before-close="handleClose">
      <div class="demo-drawer__content">
        <el-form :model="addUserForm" status-icon :rules="rules" ref="addUserForm" label-width="100px"
                 class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input type="text" v-model="addUserForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addUserForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="用户是否启用">
            <el-switch v-model="addUserForm.enabled"></el-switch>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input type="text" v-model="addUserForm.nickname" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <div class="image-container" @mouseenter="showButton" @mouseleave="hideButton">
              <el-image v-if="avatar" :src="avatar" class="avatar"></el-image>
              <div class="buttons">
                <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary"
                           @click.stop="upload">图库上传
                </el-button>
                <el-upload :http-request="fileRequest"
                           action="" ref="upload">
                  <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary">本地上传
                  </el-button>
                </el-upload>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="button-box">
          <el-button @click="close ">取 消</el-button>
          <el-button type="primary" @click="addUserSubmit" :loading="loading">
            {{ loading ? '添加中 ...' : '确 定' }}
          </el-button>
        </div>

      </div>
    </el-drawer>
    <!--编辑用户-->
    <el-drawer
        title="编辑用户"
        :visible.sync="updateWin"
        direction="rtl"
        size="40%"
        :before-close="handleClose">
      <div class="demo-drawer__content">
        <el-form :model="editUserForm" status-icon :rules="rules" ref="editUserForm" label-width="100px"
                 class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input :disabled="true" type="text" v-model="editUserForm.username"
                      placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="editUserForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="用户是否启用">
            <el-switch :disabled="true" v-model="editUserForm.enabled"></el-switch>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input type="text" v-model="editUserForm.nickname" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <div class="image-container" @mouseenter="showButton" @mouseleave="hideButton">
              <el-image v-if="avatar" :src="avatar" class="avatar"></el-image>
              <div class="buttons">
                <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary"
                           @click.stop="upload">图库上传
                </el-button>
                <el-upload :http-request="fileRequest"
                           action="" ref="upload">
                  <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary">本地上传
                  </el-button>
                </el-upload>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer button-box">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="editSubmit" :loading="loading">
            {{ loading ? '添加中 ...' : '确 定' }}
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!--关联角色-->
    <el-dialog title="关联角色" :visible.sync="dialogFormRoles" width="360px">
      <el-form :model="rolesForm" class="demo-ruleForm">
        <el-form-item style="margin-left: 50px">
          <!--<div v-for="(item, index) in rolesForm.role" :key="index">-->
          <el-select v-model="rolesForm.describe" multiple placeholder="请选择"
                     @change="change">
            <el-option v-for="(item,index) in rolesForm.roles" :label="item.describe" :value="item.roleName"
                       :key="index"></el-option>
          </el-select>
          <!--</div>-->

        </el-form-item>
      </el-form>
      <div slot="footer" class="el-dialog--center">
        <el-button @click="dialogFormRoles = false">取 消</el-button>
        <el-button type="primary" @click="handleRolesSure">确 定</el-button>
      </div>
    </el-dialog>

    <!--图库-->
    <el-dialog title="上传文件"
               :visible.sync="fileWin" width="1000px">
      <div class="dialog-height">
        <div class="img-box">
          <el-radio-group v-model="selectedIndex" size="small">
            <el-radio-button :label="index" v-for="(item, index) in fileList" :key="index">
              <el-image @click="selectImage(item.avatar)" style="width: 200px; height: 200px"
                        :src="item.avatar"></el-image>
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <el-button @click="fileWin = false">取 消</el-button>
      <el-button @click="fileWin = false" type="primary">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import ListView from "@/views/layout/listView.vue";
import HeaderView from "@/views/layout/headerView.vue";
import {
  getUserList,
  addUser,
  updateUser,
  deleteUser,
  enableUser,
  bindUserRole,
  getResource,
  uploadResource
} from "@/api/common";
import {completionUrl, splitImageUrl} from "@/utils/common";
import {formatDate} from "@/utils/dateTimeFormatter";

export default {
  name: 'home',
  components: {
    HeaderView, ListView
  },

  data() {
    return {
      // 添加用户侧边框
      addWin: false,
      loading: false,

      // 修改用户侧边框
      updateWin: false,

      // 关联提示框
      dialogFormRoles: false,

      // 请求的用户信息
      tableData: [],

      // 校验表格图片地址
      tableImageUrl: 'http://dyw770.top:18080/resource/',

      // 文件窗口
      // 服务器图片
      fileWin: false,
      fileList: [],
      selectedImageUrl: '',
      selectedIndex: null,
      showButtons: true,
      // 本地图片
      avatar:'',

      // 分页
      page: 0,
      size: 10,
      total: 0,
      currentPage: 1,
      // 搜索
      queryUserForm: {
        user: '',
      },
      // 添加表单
      addUserForm: {
        username: '',
        password: '',
        accountNonLocked: true,
        enabled: true,
        nickname: '',
        avatar: ''
      },
      // 修改表单
      editUserForm: {
        username: '',
        password: '',
        accountNonLocked: true,
        enabled: true,
        nickname: '',
        avatar: ''
      },
      // 关联表单
      rolesForm: {
        describe: [],
        role: [],
        roles: [
          {
            roleName: "ADMIN",
            describe: "管理员"
          },
          {
            roleName: "USER",
            describe: "普通用户"
          }
        ],
      },

      // 表单效验
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
        nickname: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
        ],
        avatar: [
          {required: true, message: '请上传头像', trigger: 'blur'},
        ],
      },

    }
  },
  created() {
    this.reqUserList()
  },
  methods: {
    formatDate,
    // 昵称搜索
    queryUser() {
      this.reqUserList()
    },
    // 请求用户列表数据
    reqUserList() {
      // 请求参数
      const data = {
        "page": this.page,
        "size": this.size,
        "orders": [
          {
            "column": "1",
            "asc": true
          }
        ],
        "username": "",
        "nickname": this.queryUserForm.user,
        "offset": 0
      }
      getUserList(data).then(response => {
        console.log(response)
        response.data.data.records.forEach(item => {
          // 图片处理
          item.avatar = completionUrl(item.avatar)
        })
        // 获取到总的数据数组
        this.tableData = response.data.data.records
        // 获取数据总数
        this.total = response.data.data.total
      }).catch(error => {
        console.log(error)
      })
    },

    // 添加用户
    addUserSubmit() {
      this.$confirm('确认提交？')
          .then(() => {
            this.loading = true

            // 添加用户请求
            addUser(this.addUserForm)

            setTimeout(() => {
              this.close()
              // 提交数据后清空表单
              this.$refs['addUserForm'].resetFields()

              // 重新请求 刷新
              this.reqUserList()

              this.$message({
                type:"success",
                message:"添加成功"
              })
            }, 1000)

          })
          .catch(() => {
            this.close()
          });
    },

    // 点击编辑事件
    handleEdit(row) {
      console.log(row)
      this.updateWin = true
      this.avatar=row.avatar
      this.editUserForm = row
    },
    // 编辑用户
    editSubmit() {
      this.$confirm('确认提交？')
          .then(() => {
            // 图片处理
            this.avatar = splitImageUrl(this.avatar)
            // 返回后端参数
            const data = {
              password: this.editUserForm.password,
              nickname: this.editUserForm.nickname,
              avatar: this.avatar
            }

            // 修改请求
            updateUser(data, this.editUserForm.username)

            setTimeout(() => {
              // 提交数据后清空表单
              this.$refs['editUserForm'].resetFields()
              // 重新请求 刷新
              this.reqUserList()
              this.close()
            }, 1000)
          })
          .catch(() => {
            this.close()
          });
    },

    // 删除用户
    handleDelete(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: '提示',
        message: h('p', null, '确定删除，是否继续？'),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            setTimeout(() => {
              done();
              instance.confirmButtonLoading = false;
            }, 300);
          }
          done();
        }
      }).then(() => {
        // 删除请求
        deleteUser(row.username)
        // 重新请求 刷新
        this.reqUserList()
      }).catch(() => {})

    },

    // 本地文件上传 自定义上传
    fileRequest(f) {
      let file=f.file
      const formData=new FormData
      formData.append('file',file)
      //upload为上传的接口
      uploadResource('avatar',formData).then(res => {
        this.addUserForm.avatar=res.data.data
        this.avatar= completionUrl(res.data.data)
      });
    },

    // 服务器图库上传
    upload() {
      this.fileWin = true
      // console.log("点击了图库")

      // 图库请求
      getResource('avatar').then(response => {
        response.data.data.forEach(item => {
          // 处理图片
          var avatar = completionUrl(item)
          // 添加列表
          this.fileList.push({avatar: avatar})
        })
      })
    },

    // 选中的图片
    selectImage(avatar) {
      this.avatar=avatar
      this.addUserForm.avatar = splitImageUrl(avatar)
      this.editUserForm.avatar = splitImageUrl(avatar)
    },

    // 请求修改用户启用状态
    reqEnableUser(username, enable) {
      const data = {
        username: username,
        enable: enable
      }
      enableUser(username, data).then(response => {
        console.log(response)
      })
    },

    // 修改用户是否启用状态
    handleSwitch(enabled) {
      console.log("enabled：", enabled)
      const h = this.$createElement;
      this.$msgbox({
        title: '提示',
        message: h('p', null, '确定删除，是否继续？'),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            setTimeout(() => {
              done();
              instance.confirmButtonLoading = false;
            }, 300);
          }
          done();
        }
      }).then(() => {
        // 修改请求
        this.reqEnableUser(enabled.username, enabled.enabled)

        // 修改后重新发起请求刷新
        this.reqUserList()
      }).catch(() => {
        this.reqEnableUser(enabled.username, !enabled.enabled)
        this.reqUserList()
      })
    },

    // 请求用户绑定角色
    reqBindUserRole(username, roles) {
      bindUserRole(username, roles).then(response => {
        console.log(response)
      })
    },
    // 关联角色下拉框
    change(val) {
      const roles = []
      if (val[0] === this.rolesForm.roles[0].roleName) {
        roles.push(this.rolesForm.roles[0])
      }
      if (val[1] === this.rolesForm.roles[1].roleName) {
        roles.push(this.rolesForm.roles[1])
      }
      this.rolesForm.role = roles
    },
    // 点击关联角色
    handleRoles(row) {
      this.dialogFormRoles = true
      this.rolesForm.describe = row.roles
      this.username = row.username;
    },
    // 绑定关联角色
    handleRolesSure() {
      this.dialogFormRoles = false
      console.log(this.rolesForm.describe)
    },

    // 关闭侧边栏 提示信息
    handleClose() {
      this.$confirm('确认关闭？')
          .then(() => {
            this.close()
          })
          .catch(() => {});
    },

    // 关闭添加/修改侧边栏
    close() {
      if (this.addWin) {
        this.addWin = !this.addWin
      }
      if (this.updateWin) {
        this.updateWin = !this.updateWin
      }
      this.loading = false;
    },

    // 分页
    // 每页的条数
    handleSizeChange(val) {
      this.size = val
      this.reqUserList()
    },
    // 当前页
    handleCurrentChange(val) {
      this.page = val
      this.reqUserList()
    },

    // 上传图片选择按钮
    showButton() {
      this.showButtons = true;
    },
    hideButton() {
      this.showButtons = false;
    },

  }
}
</script>

<style scoped lang="scss">
.dialog-height {
  height: 600px;
  overflow-y: auto;
}

.image-container {
  display: flex;
  flex-direction: column;
  width: 148px;
  height: 148px;
  border: 1px dotted skyblue;
  border-radius: 4px
}

.image-container {
  position: relative;
  margin: 10px;
}

.buttons {
  position: absolute;
  display: flex;
  flex-direction: column;
  margin: 30px 30px;
}

.image-container:hover button {
  display: block;
}

/*img {
  width: 45px;
  height: 45px;
  border-radius: 50%;
}*/
.img-box {
  display: inline;
  cursor: pointer;
  margin: 2px;
}

// 表格图片
.el-image__error, .el_image, img {
  width: 45px;
  height: 45px;
  border-radius: 50%;
}

// 表单
.demo-drawer__content {
  padding: 10px;
  margin: 10px;
}

// 表单按钮
.button-box {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
}

// 分页
.block {
  width: 100%;
  display: flex;
  justify-content: center;
}

</style>